// @flow
import React from 'react'
import styles from './DevicePoint.css'
import { AgGridReact } from 'ag-grid-react'
import { TableResize } from 'ag-grid-addons'
import { Row, Col, Select, message, InputNumber, TreeSelect, Icon, Input, Modal, notification } from 'antd'
const Option = Select.Option
import R from 'ramda'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import VarComp from 'components/VarCompDeviceReadOnly'
import Limits from 'components/LimitsDeviceReadOnly'
import ReactDom from 'react-dom'
const TreeNode = TreeSelect.TreeNode
message.config({
  top: 100
})

const columnDefs = [{
  headerName: '测点名称',
  field: 'sensorName',
  cellStyle: {
    'padding': '8px',
    'text-align':'left'
  }
}, {
  headerName: '通道名称',
  field: 'channelName',
  cellStyle: {
    'padding': '8px',
    'text-align':'left'
  }
}]

type Props = {
  location: Object,
  deviceId: number
}
type States = {
  pointData: Array<Object>,
  visibleLimit: boolean,
  varData: Array<any>,
  limitsData: Array<Object>,
  monitorPointId: string
}
class DevicePoint extends React.Component {
  state: States
  props: Props
  api: Object
  gridOptions: Object
  getPointData: Function
  onGridReady: Function
  TableResize: Function
  getVarData: Function
  getVarLimits: Function
  handleLimitCancel: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      pointData: [],
      visibleLimit: false,
      varData: [],
      limitsData: [],
      monitorPointId: ''
    }
    this.gridOptions = {
      pagination: false,
      animation: true,
      rowSelection: 'multiple',
      enableColResize: true,
      localeText: {
        loadingOoo: '数据加载中...',
        noRowsToShow: '暂无数据',
        filterOoo: '搜索当前页面',
        equals: '等于',
        notEqual: '不等于',
        contains: '包含',
        startsWith: '开始于',
        endsWith: '结束于',
        copy: '复制',
        paste: '粘贴',
        copyWithHeaders: '带表头复制',
        toolPanel: '工具栏',
        export: '导出',
        csvExport: '导出CSV',
        excelExport: '导出Excel'
      },
      enableSorting: true,
      enableFilter: true,
      onSelectionChanged: () => {
        const selections = this.api.getSelectedRows()
        const { deviceId } = this.props
        this.getVarData(deviceId, selections[0].id)
      },
      onModelUpdated: () => {
        if (this.api) {
          this.api.sizeColumnsToFit()
        }
      }
    }
    this.onGridReady = this.onGridReady.bind(this)
    this.TableResize = TableResize.bind(this)
    this.getPointData = this.getPointData.bind(this)
    this.getVarData = this.getVarData.bind(this)
    this.getVarLimits = this.getVarLimits.bind(this)
    this.handleLimitCancel = this.handleLimitCancel.bind(this)
  }

  componentWillMount () {
    this.getPointData()
  }

  // componentWillReceiveProps (nextProps: Object) {
  //   const component = this
  //   if (!R.equals(nextProps, this.props)) {
  //   }
  // }

  onGridReady (params: Object) {
    this.api = params.api
    this.api.sizeColumnsToFit()
    this.TableResize()
  }

  getPointData () {
    const { deviceId } = this.props
    universalFetch(`${__SERVICE_API__}device/devices/points?root_id=${deviceId}`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({
          code: json.code,
          message: json.message
        }))
      }
      this.setState({
        pointData: json.result
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }

  getVarData (deviceId: string, monitorPointId: string) {
    const url = `${__SERVICE_API__}device/devices/monitors/variables` +
      `?deviceId=${deviceId}&monitorPointId=${monitorPointId}`
    universalFetch(url)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          varData: json.result,
          monitorPointId: monitorPointId
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getVarLimits (data: Object) {
    universalFetch(`${__SERVICE_API__}device/devices/monitors/limits?` +
      `variableId=${data.id}&monitorPointId=${data.monitorPointId}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          visibleLimit: true,
          limitsData: json.result,
          monitorPointId: data.monitorPointId
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  handleLimitCancel () {
    this.setState({
      visibleLimit: false
    })
  }

  render () {
    const { pointData, varData, monitorPointId, visibleLimit, limitsData } = this.state
    const { deviceId } = this.props
    return (
      <div className={styles['main']}>
        <Row>
          <Col span={6} style={{ height: 400 }}>
            <AgGridReact {...{
              gridOptions: this.gridOptions,
              rowHeight: '34',
              headerHeight: '28',
              columnDefs: columnDefs,
              rowData: pointData,
              onGridReady: this.onGridReady
            }} />
          </Col>
          <Col span={18} style={{ height: 400 }}>
            <VarComp {...{
              varData,
              pointData,
              deviceId,
              monitorPointId,
              refreshLimit: this.getVarLimits
            }} />
            <Modal
              title='阈值'
              visible={visibleLimit}
              onCancel={this.handleLimitCancel}
              footer={null}
              >
              <Limits {...{
                limitsData
              }} />
            </Modal>
          </Col>
        </Row>
      </div>
    )
  }
}

export default DevicePoint
